package com.huijiet.base.utils;

import lombok.extern.slf4j.Slf4j;

import java.net.URL;

@Slf4j
public class SystemUtil {

    /**
     * 是否以jar包的方式运行
     *
     *  如果是jar包的方式运行,所有内容都已打包好
     *      图片访问地址不需要前缀
     *  如果不是jar包的方式运行,前后端分离.
     *      图片访问地址加上前缀
     *      http://127.0.0.1:80
     * */
    public static boolean runWithJar(){
        URL url = SystemUtil.class.getResource("");
        String protocol = url.getProtocol();
        System.out.println("protocol:" + protocol);
        if("jar".equals(protocol)){
            //以jar的方式在运行
            return true;
        }
        return false;
    }

    /**以jar包方式运行时,jar文件的所在的目录*/
    public static String jarLocation(){

        URL url = SystemUtil.class.getResource("");
        String path = url.getPath();
        if(path.startsWith("file")){
            path = path.substring(6);
        }
        int indexJar = path.indexOf("jar!");
        if(indexJar<=0){
            return null;
        }
        path = path.substring(0,indexJar);

        int indexDir = path.lastIndexOf("/");
        if(indexDir<=0){
            return null;
        }
        path = path.substring(0, indexDir);

        log.error("jar-path: {}",path);

        if(!osWindows()){
            if(!path.startsWith("/")){
                log.error("path not start with / ");
                path = "/" + path;
            }else{
                log.error("path start with /");
            }
        }else{
            log.error("os is windows");
        }

        return path;
    }

    private static boolean osWindows(){
        String osName = System.getProperty("os.name");
        if(osName.toLowerCase().startsWith("win")){
            return true;
        }else {
            return false;
        }
    }
}
